package a.codetop;

import org.junit.Test;
import 其他.DataStructure.ListNode;

public class _2k个一组反转链表 {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null)return null;
        //暂存头，反转链表工具用
        ListNode tH=head;
        //最后一节不够k
        for (int i = 0; i < k - 1; i++) {
            head=head.next;
            if(head==null)return tH;//head是tail尾了，用tH
        }


        //向下暂存节点
        ListNode faH = reverseKGroup(head.next,k);
        //向上1切2反转返回nH
        head.next=null;
        ListNode nH = fanzhuan(tH);
        tH.next=faH;
        return nH;
    }

    //工具：给一个切好的只有head的，反转
    ListNode fanzhuan(ListNode head){
        ListNode fir = head; if(fir==null)return null;
        ListNode sec = fir.next;
        while(sec!=null){
            ListNode tmp = sec.next;
            sec.next=fir;
            fir=sec; sec=tmp;
        }
        head.next=null;
        return fir;
    }
}
